package com.polaris.live.adapter.message

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.R.color
import com.polaris.live.common.adapter.BaseAdapter
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.util.AppCodeUtils.arTo
import com.polaris.live.databinding.AdapterSessionBinding
import com.polaris.live.im.db.entity.SessionEntity
import com.polaris.live.im.sfs.COMMAND_STRANGER_MESSAGE
import com.polaris.live.im.sfs.COMMAND_SYSTEM_MESSAGE
import com.polaris.live.im.utils.SessionUtils
import com.polaris.live.translation.R.string
import com.polaris.live.utils.state.UserStateUtils
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.country.countryIcons

/**
 * 会话列表的adapter
 *
 * @author Created by 半仙 on 2023/9/4/004 12:52
 */
class SessionAdapter : BaseAdapter<SessionEntity, SessionViewHolder>(R.layout.adapter_session) {

    private var sessionCommand: String? = null

    init {
        addChildClickViewIds(R.id.avatar)
    }

    override fun convert(holder: SessionViewHolder, item: SessionEntity) {
        holder.binding.apply {
            if (item.command == COMMAND_SYSTEM_MESSAGE || item.command == COMMAND_STRANGER_MESSAGE) {
                initTag(holder.binding)
                if (item.command == COMMAND_SYSTEM_MESSAGE) {
                    avatar.setImageResource(R.drawable.ic_round_launcher)

                    nickname.text =
                        "${context.getString(string.app_name)} ${context.getString(string.team)}"
                } else {
                    avatar.setImageResource(R.drawable.icon_message_list_stranger)

                    nickname.text = StringUtils.getString(string.strangers_message)
                }
                nickname.setTextColor(ColorUtils.getColor(color.color_202028))

                userCountry.visibility = View.GONE
                levelView.visibility = View.GONE

                vState.visibility = View.GONE
                ivStateLive.visibility = View.GONE
                sessionText.text = (SessionUtils.formatSessionContext(item) ?: "").arTo()
                sessionText.setTextColor(ColorUtils.getColor(color.color_a7a8ad))
            } else if (item.command == CommonConst.Customer.command) {
                avatar.setImageResource(R.drawable.ic_kefu_message)
                nickname.text = StringUtils.getString(string.customer_service_string)
            } else {

                //这里不可能为空，所以不做为空时的处理
                item.userBasic?.let { userBasic ->
                    avatar.setImageUrl(userBasic.avatar, userBasic.userId)
                    nickname.text = userBasic.nickname
                    nickname.setNicknameColor(
                        userBasic.nicknameColor,
                        color.color_202028
                    )
                    llFlag.setLabel(userBasic.label)
                    avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(userBasic.avatarFrame))
                    val country = countryIcons[userBasic.country]
                    if (country == null) {
                        userCountry.visibility = View.GONE
                    } else {
                        userCountry.visibility = View.VISIBLE
                        userCountry.setCountry(userBasic.country)
                    }

                    if (userBasic.official == 0L) {
                        ivOfficial.visibility = View.GONE
                    } else {
                        ivOfficial.visibility = View.VISIBLE
                    }
                    vipView.setVipLevel(userBasic.vipLevel)
                    levelView.visibility = View.VISIBLE
                    levelView.setRichCharmBySexLevel(
                        userBasic.sex,
                        userBasic.richs,
                        userBasic.charms
                    )

                    if (!item.isUpdatedState()) {
                        vState.visibility = View.GONE
                        ivStateLive.visibility = View.GONE
                        tvState.visibility = View.GONE
                    } else {
                        userState(holder.binding, item)
                    }
                }
                sessionText.text = (SessionUtils.formatSessionContext(item) ?: "").arTo()

            }

            if (item.timestamp == null) {
                sessionTime.visibility = View.INVISIBLE
            } else {
                sessionTime.visibility = View.VISIBLE
                sessionTime.text =
                    SessionUtils.formatSessionTime(item.timestamp)?.convertArabicDigitsToNormal()
            }

            val unreadCount = if (isSystemMessage()) {
                item.unreadCount
            } else {
                item.strangerUnreadCount
            }

            if (unreadCount == null || unreadCount <= 0) {
                tvUnreadCount.visibility = View.INVISIBLE
            } else {
                tvUnreadCount.visibility = View.VISIBLE
                tvUnreadCount.text = if (unreadCount > 99) {
                    "99+"
                } else {
                    unreadCount.toString()
                }
            }

            cosCenter.setOnLongClickListener(object : View.OnLongClickListener {
                override fun onLongClick(v: View?): Boolean {
                    onItemLongClickListener?.invoke(
                        this@SessionAdapter,
                        holder.absoluteAdapterPosition
                    )
                    return true
                }

            })
        }
    }

    private fun initTag(binding: AdapterSessionBinding) {
        binding.apply {
            vipView.setVipLevel(null)
            ivOfficial.visibility = View.GONE
            vRoundState.visibility = View.GONE
            tvState.visibility = View.GONE
            ivStateLive.visibility = View.GONE
            vState.visibility = View.GONE
            llFlag.setLabel(emptyList())
            sessionText.text = ""
            userCountry.visibility = View.GONE
            levelView.visibility = View.GONE
            avFv.setFrameImage(null)
        }
    }

    private fun userState(mBinding: AdapterSessionBinding, item: SessionEntity) {
        item.userBasic?.let { userBasic ->
            val state = UserStateUtils.resolveUserState(userBasic)
            if (state == UserStateUtils.USER_STATE_OFFLINE) {
                mBinding.ivStateLive.visibility = View.VISIBLE
                mBinding.vState.visibility = View.INVISIBLE
                mBinding.tvState.visibility = View.GONE
                mBinding.ivStateLive.setBackgroundResource(R.drawable.shape_session_state_offline)
            } else {
                mBinding.ivStateLive.visibility = View.VISIBLE
                mBinding.vState.visibility = View.INVISIBLE
                mBinding.tvState.visibility = View.GONE
                mBinding.ivStateLive.setBackgroundResource(R.drawable.ic_user_space)
            }
            when (state) {
                UserStateUtils.USER_STATE_PARTY_VIDEO, UserStateUtils.USER_STATE_PARTY, UserStateUtils.USER_STATE_GAME -> {
                    mBinding.tvState.visibility = View.VISIBLE
                    mBinding.ivStateLive.visibility = View.GONE
                    if (userBasic.avatarFrame?.isNotEmpty() == true) {
                        mBinding.vState.visibility = View.VISIBLE
                    } else {
                        mBinding.vState.visibility = View.INVISIBLE
                    }
                    when (state) {
                        UserStateUtils.USER_STATE_PARTY -> {
                            mBinding.vState.setBackgroundResource(R.drawable.community_recommend_party)
                            mBinding.tvState.text = StringUtils.getString(string.party)
                            mBinding.tvState.setBackgroundResource(R.drawable.community_recommend_text_back_party)
                        }

                        UserStateUtils.USER_STATE_PARTY_VIDEO -> {
                            mBinding.vState.setBackgroundResource(R.drawable.community_recommend_party)
                            mBinding.tvState.text = StringUtils.getString(string.video_party)
                            mBinding.tvState.setBackgroundResource(R.drawable.community_recommend_text_back_party)
                        }

                        UserStateUtils.USER_STATE_GAME -> {
                            mBinding.vState.setBackgroundResource(R.drawable.community_recommend_game)
                            mBinding.tvState.text = StringUtils.getString(string.diamond_game)
                            mBinding.tvState.setBackgroundResource(R.drawable.community_recommend_text_back_game)
                        }
                    }
                }

                else -> {
                    mBinding.vState.setBackgroundResource(0)
                    mBinding.tvState.visibility = View.GONE
                }
            }
        }
    }

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): SessionViewHolder {
        val binding =
            AdapterSessionBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SessionViewHolder(binding)
    }

    //这里之所以手动写这个方法  是因为不知道什么原因长按被拦截了所以没有触发事件
    //如果是自定义的viewHodel不能用BaseBindingAdapter因为外侧识别viewhodel是识别不到的
    private var onItemLongClickListener: ((adapter: SessionAdapter, position: Int) -> Unit)? = null
    fun setOnItemLongClickListener(l: (adapter: SessionAdapter, position: Int) -> Unit) {
        onItemLongClickListener = l
    }

    fun setSessionCommand(sessionCommand: String) {
        this.sessionCommand = sessionCommand
    }

    private fun isSystemMessage(): Boolean {
        return sessionCommand == COMMAND_SYSTEM_MESSAGE
    }

}

class SessionViewHolder(val binding: AdapterSessionBinding) : BaseViewHolder(binding.root) {

    val builder = XPopup.Builder(binding.root.context)
        .hasShadowBg(false)
        .watchView(itemView)

}